package com.yangjie.log;

import java.lang.reflect.Field;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;

public class LoggerPostProcessor implements BeanPostProcessor {
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
			public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

				if (field.getAnnotation(Inject.class) != null && field.getType().equals(LoggerIF.class)) {
					ReflectionUtils.makeAccessible(field);
					Log4jLogger logger = (Log4jLogger) field.get(bean);
					// Log4jLogger logger =
					// (Log4jLogger)(field.getType().newInstance());
					System.out.println("set logger:" + bean.getClass());
					logger.setLogger(Logger.getLogger(bean.getClass()));
					field.set(bean, logger);

				}
			}
		});

		return bean;
	}

	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
}